package com.cw.starter.trace.filter;

/**
 * @author chenw
 * @date 2020/12/17
 */

import com.cw.starter.common.util.IdGenerator;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContextAttachment;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.MDC;

import com.cw.starter.trace.filter.constants.TraceConstants;

/**
 */
@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER}, order = -9999)
public class GlobalTraceFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = invocation.getAttachment(TraceConstants.TRACE_ID);
        if (!StringUtils.isBlank(traceId)) {
            RpcContextAttachment.getServiceContext().setAttachment(TraceConstants.TRACE_ID, traceId);
        } else { // 第一次发起调用
            traceId = IdGenerator.nextStrId();
            RpcContextAttachment.getServiceContext().setAttachment(TraceConstants.TRACE_ID, traceId);
        }
        MDC.put(TraceConstants.TRACE_ID, traceId);
        return invoker.invoke(invocation);
    }
}
